<?php

namespace Application\Utils;

class Captcha{

	//Key
    private $sname ;  
   	// 干扰点
    private $pnum  = 35;
    //干扰线
    private $lnum = 2;
    //验证码长度
    private $length = 4;
    //字体大小、验证码
    private $fontSize =16;
    private $code;
    //图片宽、图片高
    private $width =78;
    private $height = 30;
    
    public function __construct($sname=''){ 
        $this->sname = $sname ==''? 'captcha' : $sname;
        $this->code = '';
        session_start();
    }  
 
    public function setWidth( $width ){
    	$this->width = $width;
    }
    
    public function setHeight( $height ){
    	$this->height = $height;
    }
    
    public function create(){
    	Header("Content-type: image/png");  
        $this->random();  
        $this->captcha_session();       
        $im = imagecreate($this->width,$this->height);                       
        $bgColor = ImageColorAllocate($im, 35,35,35);
          
        $fontColor = ImageColorAllocate($im, 255,255,255);//设置文字颜色
        
        for ($i = 0; $i < strlen($this->code); $i++){
        	$x  = $i/$this->length * $this->width + rand(1, 6); 
            $y  = rand(1, $this->height/3);                   
        	imagestring($im, $this->fontSize, $x, $y, substr($this->code,$i,1), $fontColor);
        }
  
        /* 加入干扰像素 */  
       for($i=0; $i<$this->pnum; $i++){  
            $dist = ImageColorAllocate($im, mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            imagesetpixel($im, mt_rand(0,$this->width) , mt_rand(0,$this->height) , $dist);   
        }  
  
         /* 加入干扰线 */ 
        for($i=0; $i<$this->lnum; $i++){  
        	$dist = ImageColorAllocate($im, mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            imageline($im,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$dist);  
        } 
  
        ImagePNG($im);      
        ImageDestroy($im);
    }
    
    public function check($captcha){  
        if(empty($captcha)){  
            return false;  
        }else{  
            if(strtolower($captcha)==$this->get_capcha()){
                return true;  
            }else{  
                return false;  
            }  
        }  
    }  
       
    private function random(){   
        $chars = 'abcdefghijkmnpqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXYZ23456789';  
        $max = strlen($chars) - 1;  
        for($i = 0; $i < $this->length; $i++) {  
            $this->code .= $chars[mt_rand(0, $max)];  
        }   
    }  
    private function get_capcha(){
    	return isset($_SESSION[$this->sname])? $_SESSION[$this->sname]:'';
    }
    private function captcha_session(){
        $_SESSION[$this->sname] = strtolower($this->code);
    }  
  
} 